package com.dpwgc.consumer.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dpwgc.consumer.model.Dn;
import com.dpwgc.consumer.utils.RedisUtil;
import com.dpwgc.consumer.utils.ResultUtil;
import com.dpwgc.consumer.utils.RocketMQUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * 负载均衡拦截器（POST请求）
 */
@ResponseBody
@RestController
@Component
public class LoadBalancedInterceptor implements HandlerInterceptor {

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private RocketMQUtil rocketMQUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        try{

            //跨域
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            //获取请求地址
            String uri = request.getRequestURI();

            //获取请求参数的key
            Enumeration<String> keyMap = request.getParameterNames();

            Map<String, Object> params = new HashMap<>();

            //枚举key，获取请求参数的value
            while (keyMap.hasMoreElements()) {
                String key = keyMap.nextElement();
                Object value = request.getParameter(key);
                //添加请求参数
                params.put(key, value);
            }

            //获取请求头的参数
            String uuid = request.getHeader("uuid");
            String token = request.getHeader("token");

            /**
             * 如果是创建订单的请求-则将订单数据插入消息队列
             */
            if(uri.equals("/Dn/createDn")){

                ResultUtil<Object> resultUtil = new ResultUtil<>();

                if (uuid==null){
                    resultUtil.setMsg("请登陆后访问");
                    resultUtil.setCode(440);
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(resultUtil));
                    writer.flush();
                    return false;
                }

                Object resToken = redisUtil.get(uuid);
                String strToken = String.valueOf(resToken);

                /**
                 * 通过登录验证
                 */
                if (strToken.equals(token)){

                    //解析请求参数
                    Dn dn = JSON.parseObject(JSON.toJSONString(params), Dn.class);

                    System.out.println(dn.toString());

                    //将订单插入消息队列
                    boolean flag = rocketMQUtil.pushMessage(dn);

                    //插入成功
                    if(flag){
                        resultUtil.setCode(200);
                        resultUtil.setMsg("订单已提交");
                        resultUtil.setData(dn);
                    }
                    //插入失败
                    else {
                        resultUtil.setCode(100);
                        resultUtil.setMsg("订单提交失败");
                    }

                    //返回参数
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(resultUtil));
                    writer.flush();
                    writer.close();

                    return false;

                }else {
                    resultUtil.setMsg("请登陆后访问");
                    resultUtil.setCode(440);
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(JSON.toJSONString(resultUtil));
                    writer.flush();
                    return false;
                }
            }

            /**
             * 如果是其他请求-则进行负载均衡分配
             */
            //请求头设置
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/x-www-form-urlencoded");
            headers.add("uuid", uuid);
            headers.add("token", token);

            //向生产者发送请求
            JSONArray result = restTemplate.postForObject("http://provider"+uri,params,JSONArray.class);

            //格式化服务生产者返回的数据（转化为数组）
            int j=0;
            Object[] data = new Object[result.size()-2];
            for(int i=2;i<result.size();i++){
                data[j] = result.get(i);
                j++;
            }

            ResultUtil<Object> resultUtil = new ResultUtil<>();
            resultUtil.setCode(Integer.parseInt(result.get(0).toString()));//提取出状态码code
            resultUtil.setMsg(""+result.get(1));//提取出返回的消息msg
            resultUtil.setData(data);//提取出返回的数据data

            //返回参数
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            writer.close();

            return false;

        }catch (Exception e){
            //跨域
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            ResultUtil resultUtil = new ResultUtil();
            resultUtil.setCode(100);
            resultUtil.setMsg("负载均衡器出错");
            //返回参数
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            writer.close();
            return false;
        }
    }
}
